package meiyunting.shiwuzhaoling.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件存储配置
 */
@Configuration
public class FileStorageConfig implements WebMvcConfigurer {

    @Value("${file.upload-dir}")
    private String uploadDir;
    
    private String absoluteUploadDir;

    @PostConstruct
    public void init() {
        try {
            // 确保目录结构是绝对路径
            File directory = new File(uploadDir);
            if (!directory.isAbsolute()) {
                // 如果是相对路径，转换为绝对路径
                directory = new File(System.getProperty("user.dir"), uploadDir);
            }
            
            absoluteUploadDir = directory.getAbsolutePath();
            System.out.println("【初始化】上传目录的绝对路径: " + absoluteUploadDir);
            
            if (!directory.exists()) {
                boolean created = directory.mkdirs();
                if (!created) {
                    System.err.println("【警告】Failed to create upload directory: " + directory.getAbsolutePath());
                    throw new RuntimeException("Failed to create upload directory: " + directory.getAbsolutePath());
                }
                System.out.println("【初始化】Created upload directory: " + directory.getAbsolutePath());
            } else {
                System.out.println("【初始化】Using existing upload directory: " + directory.getAbsolutePath());
                // 检查目录是否可写
                if (!directory.canWrite()) {
                    System.err.println("【警告】Upload directory is not writable: " + directory.getAbsolutePath());
                }
            }
            
            // 列出上传目录中的文件
            File[] files = directory.listFiles();
            if (files != null) {
                System.out.println("【初始化】上传目录中已有" + files.length + "个文件");
                for (File file : files) {
                    System.out.println("【初始化】已有文件: " + file.getName() + " - " + file.length() + "字节");
                }
            }
        } catch (Exception e) {
            System.err.println("【错误】Could not create upload directory: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("Could not create upload directory!", e);
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        try {
            // 获取上传目录的绝对路径
            File uploadDirFile = new File(uploadDir);
            if (!uploadDirFile.isAbsolute()) {
                uploadDirFile = new File(System.getProperty("user.dir"), uploadDir);
            }
            
            // 确保路径以文件协议开头并以斜杠结尾
            String uploadPath = uploadDirFile.getCanonicalPath().replace("\\", "/");
            if (!uploadPath.endsWith("/")) {
                uploadPath += "/";
            }
            
            // 构建资源位置URL
            String fileLocation = "file:///" + uploadPath;
            System.out.println("【资源配置】上传目录资源映射: /uploads/** -> " + fileLocation);
            
            // 添加资源处理器
            registry.addResourceHandler("/uploads/**")
                    .addResourceLocations(fileLocation);
            
            // 检查文件是否可访问
            File testFile = new File(uploadDirFile, "test.txt");
            if (!testFile.exists()) {
                try {
                    if (testFile.createNewFile()) {
                        System.out.println("【资源配置】创建测试文件成功: " + testFile.getAbsolutePath());
                        testFile.delete();
                    } else {
                        System.err.println("【警告】无法在上传目录创建测试文件: " + testFile.getAbsolutePath());
                    }
                } catch (Exception e) {
                    System.err.println("【警告】测试文件创建异常: " + e.getMessage());
                }
            }
        } catch (Exception e) {
            System.err.println("【错误】配置资源处理器失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 